package com.mimo.admin.shiro.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.springframework.http.MediaType;

import com.mimo.admin.constants.HttpParams;

public class CustomPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {

  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (HttpParams.XML_HTTP_REQUEST.equalsIgnoreCase(httpRequest.getHeader(HttpParams.X_REQUESTED_WITH))) {
      SecurityUtils.getSubject().logout();

      HttpServletResponse httpResponse = (HttpServletResponse) response;
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.addHeader(HttpParams.SESSIONS_TATUS, HttpParams.UNAUTHORIZED);
      return false;
    }

    return super.onAccessDenied(request, response);
  }

}
